﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using BGShell.Forms;

namespace BGShell
{
    public sealed class BGShellWindowManager : IEnumerable<MainForm>
    {
        private readonly List<MainForm> _forms = new List<MainForm>();
        private readonly BGShellApplication _application;
        
        private MainForm _backgroundWindow;

        internal BGShellWindowManager(BGShellApplication app)
        {
            _application = app;
        }

        public int Count
        {
            get { return _forms.Count; }
        }

        public MainForm this[int index]
        {
            get { return _forms[index]; }
        }

        public MainForm BackgroundWindow
        {
            get { return _backgroundWindow; }
            internal set
            {
                _backgroundWindow = value;
            }
        }

        public void Open()
        {
            Open(null);
        }

        public void Open(Type tabType)
        {
            CreateWindow(false).Show(tabType);
        }

        public IEnumerator<MainForm> GetEnumerator()
        {
            return _forms.GetEnumerator();
        }

        internal void OpenBackground()
        {
            Debug.Assert(_backgroundWindow == null, "There already is a background window.");
            
            _backgroundWindow = CreateWindow(true);
            _backgroundWindow.OpenFirstTab();
        }

        internal bool NextCloseWillExit
        {
            get
            {
                if (_application.Arguments.IsBackground)
                {
                    return false;
                }

                return _forms.Count == 1;
            }
        }

        private void OnWindowClosed(object sender, EventArgs e)
        {
            var form = sender as MainForm;

            if (form != null)
            {
                _forms.Remove(form);
            }
            
            if (NextCloseWillExit)
            {
                _application.MainForm = _forms[0];
            }
        }

        private MainForm CreateWindow(bool isBackground)
        {
            var f = new MainForm(isBackground);
            f.FormClosed += OnWindowClosed;
            _forms.Add(f);

            if (NextCloseWillExit)
            {
                _application.MainForm = f;
            }

            return f;
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return _forms.GetEnumerator();
        }
    }
}
